package com.hust.fastdev.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hust.fastdev.form.UserForm;
import com.hust.fastdev.model.User;
import com.hust.fastdev.service.UserService;
import com.hust.fastdev.utils.BaseResult;
import com.hust.fastdev.utils.JSONUtils;
import com.mysql.jdbc.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 
 * @since 2020-03-04
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/add")
    public String add(User u){
        BaseResult base = new BaseResult();
        boolean result = u.insert();
        if(result){
            base.setCode( 200 );
        }else{
            base.setCode( 400 );
        }
        return JSON.toJSONString(base);
    }
    @RequestMapping("/update")
    public String update(User u){
        BaseResult base = new BaseResult();
        boolean result = u.updateById();
        if(result){
            base.setCode( 200 );
        }else{
            base.setCode( 400 );
        }
        return JSON.toJSONString(base);
    }
    @RequestMapping("/delete")
    public String delete(User u){
        BaseResult base = new BaseResult();
        boolean result = u.deleteById();
        if(result){
            base.setCode( 200 );
        }else{
            base.setCode( 400 );
        }
        return JSON.toJSONString(base);
    }
    @RequestMapping("/selectById")
    public String selectById(User u){
        BaseResult base = new BaseResult();
        User user = u.selectById();
        base.setData(user);
        return JSON.toJSONString(base);
    }
    @RequestMapping("/list")
    public String list(UserForm form){
        BaseResult base = new BaseResult();
        QueryWrapper<User> queryWrapper =new QueryWrapper<>();
        if(!StringUtils.isNullOrEmpty(form.getUsername())){
            queryWrapper.like("username",form.getUsername());
        }
        PageHelper.startPage(form.getPageNum(),form.getPageSize());
        List<User> list = userService.list(queryWrapper);
        PageInfo<User> pageInfo = new PageInfo<User>(list);
        base.setData( pageInfo );
        return JSONUtils.toJSONString(base);
    }
}
